package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

//定义ShouldBind结构体
type User struct {
	User string `form:"user" json:"user"`
	Pwd  int    `form:"pwd" json:"pwd"`
}

func main() {

	r := gin.Default()

// 获取基本的请求信息
	r.Any("/basicInfo", func(context *gin.Context) {
		// 请求请求信息
		// 请求方式
		fmt.Println("Method:", context.Request.Method) //Method: GET
		// 请求URl
		fmt.Println("URL:", context.Request.URL) //URL: /basicInfo?index=1
		fmt.Println("FullPath:", context.FullPath())//FullPath: /basicInfo
		// 请求头
		fmt.Println("context.Header:", context.Request.Header)
		fmt.Println("user-agent:", context.GetHeader("user-agent"))//user-agent: PostmanRuntime/7.29.2
		fmt.Println("Postman-Token:", context.GetHeader("Postman-Token"))//Postman-Token: 3b433801-9db7-4af9-938c-d2f5ac1b4048
		// IP和端口
		fmt.Println("RemoteAddr:", context.Request.RemoteAddr)//RemoteAddr: 127.0.0.1:13164
		fmt.Println("ClientIP:", context.RemoteIP())//ClientIP: 127.0.0.1
		fmt.Println("ClientIP:", context.ClientIP())//ClientIP: 127.0.0.1
		
		// 响应
		context.String(200, "basicInfo")
	})

// 获取get请求数据
	r.GET("/data", func(context *gin.Context) {
		fmt.Println("name:", context.Query("name"))
		// fmt.Println("age:", context.Query("age"))
		fmt.Println("age:", context.DefaultQuery("age", "18")) //默认值age=18
		context.String(200, "data")
	})

	r.GET("/searchJob", func(context *gin.Context) {
		xl := context.Query("xl")
		gj := context.Query("gj")
		city := context.Query("city")
		// select * from job where xl = xl and gj = gj and city= city
		context.JSON(200, gin.H{
			"data": "data数据",
			"xl":   xl,
			"gj":   gj,
			"city": city,
		})
	})

// 获取post请求数据
	//form
	r.POST("/data", func(context *gin.Context) {
		//获取请求提数据  PostForm是接受form表单格式的数据的
		user := context.PostForm("user")
		pwd := context.PostForm("pwd")
		// hobby := context.PostForm("hobby")
		hobbies := context.PostFormArray("hobbies")

		context.JSON(200, gin.H{
			"user":    user,
			"pwd":     pwd,
			// "hobby": hobby, //["篮球","足球"]
			"hobbies": hobbies, //["["篮球","足球"]"]
		})
	})

	//json
	r.POST("/shouldBind/data", func(context *gin.Context) {
		//  "{"user":"rain","pwd":123}"--->反序列化--->映射到结构体对象
		// 初始化user对象
		user := User{}
		err := context.ShouldBind(&user)
		if err != nil {
			return
		}
		//参数的处理逻辑
		if user.User == "hankai" && user.Pwd == 123 {
			context.JSON(200, gin.H{
				"user": user,
			})
		} else {
			context.JSON(200, gin.H{
				"err": "用户名或者密码错误！",
			})
		}
	})

	r.Run()

}
